package com.ruicar.afs.cloud.parameter.commom.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.condition.ChannelVehicleInfoCondition;
import com.ruicar.afs.cloud.parameter.commom.condition.VehicleCondition;
import com.ruicar.afs.cloud.parameter.commom.condition.VehicleListCondition;
import com.ruicar.afs.cloud.parameter.commom.condition.VehicleTreeCondition;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleBrand;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleDetail;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleModel;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleDetailService;
import com.ruicar.afs.cloud.parameter.commom.vo.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruicar.afs.cloud.parameter.commom.utils.ParamConstants.*;


/**
 * @description: 车型库
 * @author: sijun.yu
 * @date: 2020/5/15 14:03
 */
@Slf4j
@RestController
@RequestMapping(value = "/vehicle")
public class VehicleController {

    @Autowired
    private TsysVehicleDetailService detailService;

    /**
     * 查询品牌列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getBrandList")
    @ApiOperation("查询品牌列表")
    public IResponse<List<VehicleBrandVO>> getBrandList(@ModelAttribute VehicleCondition condition) {

        List<TsysVehicleBrand> list = detailService.getVehicleBrandList(condition);
        List<VehicleBrandVO> resultList = new ArrayList<VehicleBrandVO>();
        for (TsysVehicleBrand brand : list) {
            VehicleBrandVO vo = new VehicleBrandVO();
            vo.setBrandId(brand.getCode());
            vo.setBrandName(brand.getName());
            Character firstChar = Character.toUpperCase(brand.getSpellCode().charAt(0));
            vo.setFirstChar(firstChar);
            resultList.add(vo);
        }
        return IResponse.success(resultList);
    }

    /**
     * 查询车型列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getModelList")
    @ApiOperation("查询车型列表")
    public IResponse<List<VehicleModelVO>> getModelList(@ModelAttribute VehicleCondition condition) {

        List<TsysVehicleModel> list = detailService.getVehicleModelList(condition);
        List<VehicleModelVO> resultList = new ArrayList<VehicleModelVO>();
        for (TsysVehicleModel model : list) {
            VehicleModelVO vo = new VehicleModelVO();
            vo.setBrandId(model.getBrandCode());
            vo.setModelId(model.getCode());
            vo.setModelName(model.getFullName());
            Character firstChar = Character.toUpperCase(model.getSpellCode().charAt(0));
            vo.setFirstChar(firstChar);
            vo.setBrandName(model.getName());
            resultList.add(vo);
        }
        return IResponse.success(resultList);
    }

    /**
     * 查询款式列表
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getStyleList")
    @ApiOperation("查询款式列表")
    public IResponse<List<VehicleStyleVO>> getStyleList(@ModelAttribute VehicleCondition condition) {

        List<TsysVehicleDetail> list = detailService.getVehicleStyleList(condition);
        List<VehicleStyleVO> resultList = new ArrayList<VehicleStyleVO>();
        for (TsysVehicleDetail detail : list) {
            VehicleStyleVO vo = new VehicleStyleVO();
            vo.setStyleId(detail.getCode());
            vo.setStyleName(detail.getName());
            vo.setGuidePrice(detail.getGuidePrice());
            resultList.add(vo);
        }
        return IResponse.success(resultList);
    }


    /**
     * 获取主营品牌树状图
     *
     * @return
     */
    @RequestMapping(value = "/getCarTree", method = RequestMethod.POST)
    @ApiOperation(value = "获取品牌树状图")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<List<TsysVehicleBrand>> getCarTree(@RequestBody VehicleTreeCondition condition) {
        String[] type = condition.getType();
        String brandType = "10";
        if (type.length == 0) {
            condition.setType(null);
        } else {
            type = ArrayUtil.append(type, brandType);
            condition.setType(type);
        }
        List<TsysVehicleBrand> brandList = detailService.getBrandInfo(condition);
        //默认查询层级最上层-1层，表示品牌名称
        int level = -1;
        List<TsysVehicleBrand> permissions = brandList.stream().filter(carParam -> CAR_LEVEL.equals(carParam.getCarLevel())).collect(Collectors.toList());
        permissions.forEach(carParam -> {
            findCarParam(carParam, brandList, level);
        });
        return new IResponse<List<TsysVehicleBrand>>().setData(permissions);
    }

    /**
     * 获取车辆参数
     * @param carParam
     * @param tsysVehicleBrandParam
     * @param level
     */
    private void findCarParam(TsysVehicleBrand carParam, List<TsysVehicleBrand> tsysVehicleBrandParam, int level) {
        List<TsysVehicleBrand> children = tsysVehicleBrandParam.stream().filter(child -> carParam.getCode().equals(child.getUpperCode())).collect(Collectors.toList());
        children.forEach(child -> {
            //层级+1
            child.setCarLevel(level + 1 + "");
            findCarParam(child, tsysVehicleBrandParam, level + 1);
        });
        carParam.setChildren(children);
    }

    /**
     * 查询品牌列表提供规则使用
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getBrandListByRule")
    @ApiOperation("查询品牌列表")
    public IResponse getBrandListByRule(@RequestBody VehicleCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<RuleAtomVO>> list = detailService.getBrandListByRule(page, condition);
        return IResponse.success(list);
    }

    /**
     * 查询车型列表提供规则使用
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getModelListByRule")
    @ApiOperation("查询车型列表")
    public IResponse getModelListByRule(@RequestBody VehicleCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<RuleAtomVO>> list = detailService.getModelListByRule(page, condition);
        return IResponse.success(list);
    }

    /**
     * 查询款式列表提供规则使用
     *
     * @param condition
     * @return
     */
    @PostMapping(value = "/getStyleListByRule")
    @ApiOperation("查询款式列表")
    public IResponse getStyleListByRule(@RequestBody VehicleCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<RuleAtomVO>> list = detailService.getStyleListByRule(page, condition);
        return IResponse.success(list);
    }

    /**
     * 查询款式列表
     * @param condition
     * @return
     */
    @PostMapping(value = "/getVehicleList")
    @ApiOperation("查询款式列表")
    public IResponse<List<VehicleVO>> getVehicleList(@RequestBody VehicleListCondition condition) {
        Page page = new Page(condition.getPageNumber(), condition.getPageSize());
        IPage<List<VehicleVO>> list =detailService.getVehicleList(page,condition);
        return IResponse.success(list);
    }


    /**
     * 获取渠道上线品牌Tree
     *
     * @return
     */
    @RequestMapping(value = "/getBrandTree", method = RequestMethod.POST)
    @ApiOperation(value = "获取品牌树状图")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<List<VehicleTreeCondition>> getBrandTree(@RequestBody VehicleTreeCondition condition) {
        List<VehicleTreeCondition> list = new ArrayList<>();
        //数据库中没有品牌层级，默认插入第一层级关系
        VehicleTreeCondition tree = new VehicleTreeCondition();
        tree.setTitle("品牌名称");
        //编码
        tree.setCode(BRAND_CODE);
        //层级
        tree.setCarLevel(BRAND_LEVEL);
        //上级
        tree.setUpperCode(BRAND_UPPER_CODE);
        //给字符串null,否则前端接收不到
        tree.setCarType("null");
        list.add(tree);
        //获取品牌数据，品牌数据层级为1，上级对应品牌名称中国code=00
        List<VehicleTreeCondition> brandList = detailService.getBrandTree(condition);
        //获取车型数据 品牌数据层级为2，上级对应品牌
        List<VehicleTreeCondition> modelList = detailService.getModelTree(condition);
        if(CollectionUtil.isNotEmpty(modelList)){
            for (VehicleTreeCondition condition1 : modelList){
                condition1.setCarType("null");
            }
        }
        list.addAll(brandList);
        list.addAll(modelList);
        return new IResponse<List<VehicleTreeCondition>>().setData(buildTree(list));
    }

    /**
     * 获取层级
     * @param zoneList
     * @return
     */
    public static List<VehicleTreeCondition> buildTree(List<VehicleTreeCondition> zoneList) {
        Map<String, List<VehicleTreeCondition>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(VehicleTreeCondition::getUpperCode));
        zoneList.forEach(
                zone -> zone.children =
                zoneByParentIdMap.get(zone.getCode())
        );
        //默认查询1层级
        return zoneList.stream().filter(v -> v.getUpperCode().equals(BRAND_UPPER_CODE)).collect(Collectors.toList());
    }

    /**
     * 获取渠道上线品牌Tree
     *
     * @return
     */
    @RequestMapping(value = "/getBrandChannelTree", method = RequestMethod.POST)
    @ApiOperation(value = "获取品牌树状图")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<List<VehicleTreeCondition>> getBrandChannelTree(@RequestBody VehicleTreeCondition condition) {
        List<VehicleTreeCondition> list = new ArrayList<>();
        //数据库中没有品牌层级，默认插入第一层级关系
        VehicleTreeCondition tree = new VehicleTreeCondition();
        tree.setTitle("品牌名称");
        //编码
        tree.setCode(BRAND_CODE);
        //层级
        tree.setCarLevel(BRAND_LEVEL);
        //上级
        tree.setUpperCode(BRAND_UPPER_CODE);
        list.add(tree);
        //获取品牌数据，品牌数据层级为1，上级对应品牌名称中国code=00
        List<VehicleTreeCondition> brandList = detailService.getBrandTree(condition);
        list.addAll(brandList);
        return new IResponse<List<VehicleTreeCondition>>().setData(buildTree(list));
    }

    /**
     * 获取渠道上线品牌Tree
     *
     * @return
     */
    @RequestMapping(value = "/getModelChannelTree", method = RequestMethod.POST)
    @ApiOperation(value = "获取品牌树状图")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<List<VehicleTreeCondition>> getModelChannelTree(@RequestBody VehicleTreeCondition condition) {
        //获取车型数据 品牌数据层级为2，上级对应品牌
        List<VehicleTreeCondition> modelList = detailService.getModelTree(condition);
        ChannelVehicleInfoCondition vehicleInfoCondition = new ChannelVehicleInfoCondition();
        if(condition.getChannelId() !=null){
            vehicleInfoCondition.setChannelId(condition.getChannelId().toString());
        }
        List<VehicleTreeCondition>  list = new ArrayList<>();
        if(modelList !=null && modelList.size()>0){
            for(VehicleTreeCondition treeCondition :modelList){
                vehicleInfoCondition.setCode(treeCondition.getCode());
                ChannelVehicleInfoCondition vehicleInfo = detailService.getVehicleInfoTree(vehicleInfoCondition);
                if(vehicleInfo !=null){
                    treeCondition.setChecked(true);
                }
                list.add(treeCondition);
            }
        }
        return new IResponse<List<VehicleTreeCondition>>().setData(list);
    }
}
